<?php

namespace app\api\controller\common;

use app\api\model\mine\UsdtLogModel;
use app\api\model\order\RechargeModel;
use app\api\model\user\UserAddressModel;
use app\api\model\user\UserAssetsLogModel;
use app\api\model\user\UserAssetsModel;
use app\api\model\user\UserModel;
use app\common\controller\Api;
use GuzzleHttp\Client;
use think\Db;
use think\Exception;
use Tron\Address;
use Tron\TRX;

class Tron extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function test()
    {

        $uri = 'https://api.shasta.trongrid.io';// shasta testnet
        $api = new \Tron\Api(new Client(['base_uri' => $uri]));

        $trxWallet = new \Tron\TRX($api);
        $addressData = $trxWallet->generateAddress();
// $addressData->privateKey
// $addressData->address

        $config = [
            'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
            'decimals' => 6,
        ];
        $trc20Wallet = new \Tron\TRC20($api, $this->config);
        $addressData = $trc20Wallet->generateAddress();
    }

    public function test1()
    {
        $uri = 'https://api.shasta.trongrid.io';// shasta testnet
        $api = new \Tron\Api(new Client(['base_uri' => $uri]));

        $trxWallet = new TRX($api);
        $address = new Address('TSzy2XjGcoKkMwNpb9QSfX28gh329EfjXM');
        $res = $trxWallet->balance($address);
        dump($res);
        die;
    }


    /**
     * Notes: 余额检测
     * User: 浪子膏
     * Date: 2023/11/17 11:14
     * @throws \Tron\Exceptions\TronErrorException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkAddressBalance()
    {
        $user_ids = UserModel::whereTime('last_active_time', 'today')->column('id');
        $address = UserAddressModel::where('user_id', 'in', $user_ids)->where('type', 'usdt')
            ->field('id,user_id,address,type')->select();

        if (count($address)) {
            $uri = 'https://api.shasta.trongrid.io';// shasta testnet
            $api = new \Tron\Api(new Client(['base_uri' => $uri]));
            Db::startTrans();
            try {
                foreach ($address as $key => $item) {
                    $trxWallet = new TRX($api);
                    $address = new Address($item['address']);
                    $balance = $trxWallet->balance($address);
                    if ($key == 1) {
                        $balance = 100;
                    }
                    if ($balance > 0) {
                        $usdtLogModel = new UsdtLogModel();
                        $usdtLog = $usdtLogModel->where(['user_id' => $item['user_id'], 'address' => $item['address']])
                            ->order('id desc')->find();

                        if (!empty($usdtLog)) {
                            $balance = round($balance - $usdtLog['after'], 8);
                        }
                    }
                    if ($balance > 0) {
                        $userAssetsModel = new UserAssetsModel();
                        $userAssetsModel->addAssets($item['user_id'], $balance);
                        $userAssetsLogModel = new UserAssetsLogModel();
                        $userAssetsLogModel->createLog('usdt', $item['user_id'], $balance, UserAssetsLogModel::TYPE_REGISTER);

                        if (!empty($usdtLog)) {
                            $after = $balance + $usdtLog['after'];
                        } else {
                            $after = $balance;
                        }
                        $usdtLogModel->createLog($item['user_id'], $item['address'], $balance, $after, UsdtLogModel::TYPE_RECHARGE);

                        $rechargeModel = new RechargeModel();
                        $rechargeModel->save([
                            'user_id' => $item['user_id'],
                            'money' => $balance,
                            'address' => $item['address'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ]);
                    }
                }

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->error($exception->getMessage());

            }
        }

        $this->dataOk();
    }

}